package com.qf.util;

import com.qf.bean.Employee;
import com.qf.bean.Menu;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 2019/11/25
 * Administrator
 * ssm1119
 * 面向对象面向君  不负代码不负卿
 */
//授权拦截器
public class AuthInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //前提条件:认证通过以后
        //1.判断是否是匿名地址(公开地址)
        String requestURI = request.getRequestURI();//请求地址
        ResourceBundle anon = ResourceBundle.getBundle("anon");
        if(anon.containsKey(requestURI)){
            //属于匿名地址
            return  true;
        }
        //2.是否是公共地址
        ResourceBundle publicUri = ResourceBundle.getBundle("public");
        if(publicUri.containsKey(requestURI)){
            return true;
        }
        //3.判断请求地址属于属于当前登录的用户
        Employee user = (Employee) request.getSession().getAttribute("user");
        List<Menu> menuList = user.getRole().getMenus();
        //判断是否是菜单的请求地址
        for (Menu menu : menuList) {
            if(requestURI.equals(menu.getUrl())){
                return  true;
            }else{
                List<Menu> secondMenu = menu.getSecondMenu();
                for (Menu secondMenu1 : secondMenu) {
                    if(requestURI.equals(secondMenu1.getUrl())){
                        return  true;
                    }
                }
            }
        }
        //判断是否是permission请求的地址
        List<Menu> permissionList = user.getRole().getPermissionList();
        for (Menu menu : permissionList) {
            if(requestURI.equals(menu.getUrl())){
                return true;
            }
        }

        //4.授权失败：
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("<script>location.href='/error.jsp'</script>");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
